package com.actions;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;

import com.bean.Craft;
import com.bean.ProcureProduct;
import com.bean.ProcureProductSku;
import com.bean.ProductPart;
import com.opensymphony.xwork2.ActionSupport;
import com.serviceImpl.ProcureProductServiceImpl;
import com.serviceImpl.ProcureProductSkuServiceImpl;
import com.serviceImpl.UtilSupport;

public class ProcureproductAction extends ActionSupport {

	private static final Object[] String = null;
	private List<ProcureProduct> procureplist;
	private List<ProductPart> prodplist;
	private List<Craft> cralist;
	private List<ProcureProductSku> productSkus;	//采购明细集合
	
	private UtilSupport util;		//公用类
	private ProcureProductServiceImpl procurepBiz;	//采购需求
	private ProcureProductSkuServiceImpl procureProductSkuBiz; //采购明细service
	private JSONArray procureProductJsons;
	private ProcureProduct procureProduct;
	private ProcureProductSku procureProductSku;	//采购需求明细类
	private String skuJsons;
	private Integer partId;
	private Integer procId;
	private String param;	//发布的供应商
	
	private int offset;			//当前页
	private int pageSize=10;
	private int totalcount;		// 总记录数
	private int totalpage; 		// 总页数

	private String productCode;//款号
	private String suppelierCountSt;//开始供应商数量
	private String suppelierCountEd;//结束供应商数量
	private String createtimeSt;//开始时间
	private String createtimeEd;//结束时间
	private String status;//状态
	
	
	
	private File myFile;//封装上传的文件
	private String myFileContentType;//封装上传文件的类型
	private String myFileFileName;//封装上传文件的文件名
	private Boolean flag;	//ajax回调判断
	private Map<String, Object> jsonResult;//map集合
	
	//添加采购需求
	private String msg;//封装jsp提示语
	
	public ProcureproductAction(){
		procureplist = new ArrayList<ProcureProduct>();
		procureProductJsons = new JSONArray();
		jsonResult = new HashMap<String, Object>();
		productSkus = new ArrayList<ProcureProductSku>();
		
	}

	public Integer getPartId(){
		return partId;
	}

	public void setPartId(Integer partId) {
		this.partId = partId;
	}

	public List<Craft> getCralist() {
		return cralist;
	}
	public void setCralist(List<Craft> cralist) {
		this.cralist = cralist;
	}
	public Integer getProcId() {
		return procId;
	}
	public void setProcId(Integer procId) {
		this.procId = procId;
	}
	public JSONArray getProcureProductJsons() {
		return procureProductJsons;
	}

	public void setProcureProductJsons(JSONArray procureProductJsons) {
		this.procureProductJsons = procureProductJsons;
	}

	public String getProductCode() {
		return productCode;
	}

	public void setProductCode(String productCode) {
		this.productCode = productCode;
	}

	public List<ProcureProduct> getProcureplist() {
		return procureplist;
	}

	public void setProcureplist(List<ProcureProduct> procureplist) {
		this.procureplist = procureplist;
	}

	public UtilSupport getUtil() {
		return util;
	}

	public void setUtil(UtilSupport util) {
		this.util = util;
	}

	public ProcureProductServiceImpl getProcurepBiz() {
		return procurepBiz;
	}

	public void setProcurepBiz(ProcureProductServiceImpl procurepBiz) {
		this.procurepBiz = procurepBiz;
	}

	public ProcureProduct getProcureProduct() {
		return procureProduct;
	}

	public void setProcureProduct(ProcureProduct procureProduct) {
		this.procureProduct = procureProduct;
	}

	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalcount() {
		return totalcount;
	}

	public void setTotalcount(int totalcount) {
		this.totalcount = totalcount;
	}

	public int getTotalpage() {
		return totalpage;
	}

	public void setTotalpage(int totalpage) {
		this.totalpage = totalpage;
	}

	public String getSuppelierCountSt() {
		return suppelierCountSt;
	}

	public void setSuppelierCountSt(String suppelierCountSt) {
		this.suppelierCountSt = suppelierCountSt;
	}

	public String getSuppelierCountEd() {
		return suppelierCountEd;
	}

	public void setSuppelierCountEd(String suppelierCountEd) {
		this.suppelierCountEd = suppelierCountEd;
	}

	public String getCreatetimeSt() {
		return createtimeSt;
	}

	public void setCreatetimeSt(String createtimeSt) {
		this.createtimeSt = createtimeSt;
	}

	public String getCreatetimeEd() {
		return createtimeEd;
	}

	public void setCreatetimeEd(String createtimeEd) {
		this.createtimeEd = createtimeEd;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public List<ProductPart> getProdplist() {
		return prodplist;
	}


	public void setProdplist(List<ProductPart> prodplist) {
		this.prodplist = prodplist;
	}

	public File getMyFile() {
		return myFile;
	}

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	public String getMyFileContentType() {
		return myFileContentType;
	}

	public void setMyFileContentType(String myFileContentType) {
		this.myFileContentType = myFileContentType;
	}

	public String getMyFileFileName() {
		return myFileFileName;
	}

	public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}

	public Boolean getFlag() {
		return flag;
	}

	public void setFlag(Boolean flag) {
		this.flag = flag;
	}
	
	public Map<String, Object> getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(Map<String, Object> jsonResult) {
		this.jsonResult = jsonResult;
	}

	public ProcureProductSku getProcureProductSku() {
		return procureProductSku;
	}

	public void setProcureProductSku(ProcureProductSku procureProductSku) {
		this.procureProductSku = procureProductSku;
	}

	public String getSkuJsons() {
		return skuJsons;
	}

	public void setSkuJsons(String skuJsons) {
		this.skuJsons = skuJsons;
	}

	public ProcureProductSkuServiceImpl getProcureProductSkuBiz() {
		return procureProductSkuBiz;
	}

	public void setProcureProductSkuBiz(
			ProcureProductSkuServiceImpl procureProductSkuBiz) {
		this.procureProductSkuBiz = procureProductSkuBiz;
	}

	public List<ProcureProductSku> getProductSkus() {
		return productSkus;
	}

	public void setProductSkus(List<ProcureProductSku> productSkus) {
		this.productSkus = productSkus;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getParam() {
		return param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	/**
	 * 获取所有采购需求
	 * @return
	 */
	public String getAllProcurep(){
		HttpServletRequest request = ServletActionContext.getRequest();
		try {

			StringBuffer sqlbf=new StringBuffer("select * from audit.procure_product WHERE 0=0 ");
			String	codeSql = "";
	 		String suppelierSql = "";
	 		String statuSql = "";
	 		String timeSql="";
			//产品款号
			this.productCode = request.getParameter("productCode");
			if(productCode != null&&!productCode.isEmpty()){
				productCode=new String(productCode.trim().getBytes("ISO-8859-1"),"UTF-8");
				codeSql=" and product_code like '%"+productCode+"%'";
				sqlbf.append(codeSql);
			}
			//供应商数量
			this.suppelierCountSt = request.getParameter("suppelierCountSt");//开始数量
			this.suppelierCountEd = request.getParameter("suppelierCountEd");//结束数量
			
			if(suppelierCountSt!=null&&!suppelierCountSt.isEmpty()&&suppelierCountEd!=null&&!suppelierCountEd.isEmpty()){
				Double sSt=Double.parseDouble(suppelierCountSt);
				Double sEd=Double.parseDouble(suppelierCountEd);
				
				if (sSt<sEd) {
					suppelierSql="and( suppelier_count  between "+sSt+" and "+sEd+")";
				}else {
					suppelierSql="and( suppelier_count  between "+sEd+" and "+sSt+")";
				}
				
				sqlbf.append(suppelierSql);
			}
			//状态
			this.status = request.getParameter("status");
			if(status != null&&!status.isEmpty()){
				status=new String(status.trim().getBytes("ISO-8859-1"),"UTF-8");
				if(!status.equals("-1")){
					
					statuSql=" and status ="+status+"";
					sqlbf.append(statuSql);
				}
			}
			//跟具时间
			this.createtimeSt = request.getParameter("createtimeSt");//开始时间
			
			this.createtimeEd = request.getParameter("createtimeEd");//结束时间
			
			if(createtimeSt!=null&&!createtimeSt.isEmpty()&&createtimeEd!=null&&!createtimeEd.isEmpty()){
				//格式化时间
				SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
				
				Date sDate = sim.parse(createtimeSt);
				Timestamp s = new Timestamp(sDate.getTime());
				
				Date eDate = sim.parse(createtimeEd);
				Timestamp e = new Timestamp(eDate.getTime());
				
				
				timeSql="and (create_time  between '"+s+"' and '"+e+"')";
				
				sqlbf.append(timeSql);
			}

			
			String sql =sqlbf.toString();
			
			totalcount = util.getTotalCount(sql);		//获取总条数

			totalpage = totalcount % pageSize == 0 ? totalcount / pageSize 
					: totalcount / pageSize + 1;		//获取总页数

			offset = getPageOffset();
			
			//表名
			String table="audit.procure_product";
			//主键
			String pk="proc_id";
			//排序字段
			String sort="proc_id";
			//当前页数
			int PageNumber=offset+1;
			
			int PageSize=pageSize;

			//查询条件
			String options=(codeSql+suppelierSql+statuSql+timeSql)==null?"":"0=0"+codeSql+suppelierSql+statuSql+timeSql;
			procureplist=procurepBiz.getAllProcurep(table, pk, sort, PageNumber, PageSize, options);
		
		} catch (Exception e) {
		}
		return "procurepsuccess";
	}
	
	// Added by JSL : 获取翻页偏移量(实际上是将要翻到的页面的页索引，页索引从 0 开始)
		private int getPageOffset() {
			HttpServletRequest request=ServletActionContext.getRequest();
			String ofst = request.getParameter("offset");
			int idx = 0;
			if(ofst!=null){
				idx = Integer.valueOf(ofst);
				idx = idx < 0 ? 0 : idx;                        // 超过第一页时，不再翻页
				idx = idx >= totalpage ? (totalpage-1) : idx;	// 超过最后一页时，不再翻页		
			}
			return idx;
		}
	

		
	/**
	 * 	根据procId详细信息
	 */
	public String getDetaPurchase(){
		HttpServletRequest request=ServletActionContext.getRequest();
		
		//接受页面穿过来的值
		String id= request.getParameter("procId");
		procId=Integer.valueOf(id);
		
		//获取采购信息
		procureProduct = procurepBiz.getById(procId);
		//获取采购明细
		productSkus = procureProductSkuBiz.getPskByProcId(procId);
		
		//创建一个JSONArray
		JSONArray skuJsons=new JSONArray();
		skuJsons = JSONArray.fromObject(productSkus);
		//获取集合中的尺寸和颜色
		//创建颜色集合
		List listc=new ArrayList();
		for (int i = 0; i < productSkus.size(); i++) {
			String con = productSkus.get(i).getCona();
			listc.add(con);
		}
		//去除重复元素
		HashSet hsco = new HashSet(listc);
		
		//创建尺寸集合
		List lists=new ArrayList();
		for (int i = 0; i < productSkus.size(); i++) {
			String sz = productSkus.get(i).getSzid();
			lists.add(sz);
		}
		//去除重复元素
		HashSet hssz = new HashSet(lists);
		
	    request.setAttribute("productSkus", productSkus);
	    request.setAttribute("hsco", hsco);
	    request.setAttribute("hssz", hssz);

		
		return "deta";
	
		
	}
		
	/**
	 * 根据procId修改信息
	 * @return
	 */
	public String getEditByprocId(){
			HttpServletRequest request=ServletActionContext.getRequest();
			
			//接受页面穿过来的值
			String id= request.getParameter("procId");
			procId=Integer.valueOf(id);
			
			//获取采购信息
			procureProduct = procurepBiz.getById(procId);
			//获取采购明细
			productSkus = procureProductSkuBiz.getPskByProcId(procId);
			
			//创建一个JSONArray
			JSONArray skuJsons=new JSONArray();
			skuJsons = JSONArray.fromObject(productSkus);
			//获取集合中的尺寸和颜色
			//创建颜色集合
			List listc=new ArrayList();
			for (int i = 0; i < productSkus.size(); i++) {
				String con = productSkus.get(i).getCona();
				listc.add(con);
			}
			//去除重复元素
			HashSet hsco = new HashSet(listc);
			
			//创建尺寸集合
			List lists=new ArrayList();
			for (int i = 0; i < productSkus.size(); i++) {
				String sz = productSkus.get(i).getSzid();
				lists.add(sz);
			}
			//去除重复元素
			HashSet hssz = new HashSet(lists);
			
		    request.setAttribute("productSkus", productSkus);
		    request.setAttribute("hsco", hsco);
		    request.setAttribute("hssz", hssz);

			
			return "edit";
		}
		
	
	
	/**
	 *上传照片到服务器
	 */
	public String uploadFiles() {
		try {
			// 基于myFile创建一个文件输入流
			FileInputStream is = new FileInputStream(myFile);
			// 设置上传文件目录
			String uploadPath = ServletActionContext.getServletContext()
					.getRealPath("/drawing");
			
			File zipFile = new File(uploadPath);
			
			if(!zipFile.exists()){
				//======验证文件夹在服务器中是否存在 
				zipFile.mkdirs();//如果此文件夹不存在，自动创建此文件夹 
			}
			
			// 设置目标文件
			File toFile = new File(uploadPath, this.getMyFileFileName());
			String name=getMyFileFileName();
			//======验证文件在服务器中是否存在 
			if (!toFile.exists()) {
				toFile.createNewFile();
				//创建一个输出流
				OutputStream os = new FileOutputStream(toFile);
				// 设置缓存
				byte[] buffer = new byte[1024];
				int length = 0;
				// 读取myFile文件输出到toFile文件中
				while ((length = is.read(buffer)) > 0) {
					os.write(buffer, 0, length);
				}
				// 关闭输入流
				is.close();
				// 关闭输出流
				os.close();
				flag=true;
				jsonResult.put("name", name);
				jsonResult.put("flag", flag);
			}else{
				flag=false;
				jsonResult.put("flag", flag);
				jsonResult.put("name", "文件已存在");
			}
			
		} catch (IOException e) {
			flag=false;
			jsonResult.put("flag", flag);
			jsonResult.put("name", "文件上传失败");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	
		return "upload";
	} 
	
	/**
	 * 文件下载
	 */
	public void downFile(){
		try {
			HttpServletRequest request=ServletActionContext.getRequest();
			HttpServletResponse response=ServletActionContext.getResponse();
			//获取文件名
			String file =  request.getParameter("fileName");
			String fileName = new String(file.getBytes("iso8859-1"),"UTF-8");
			//设置文件目录
			String uploadPath = ServletActionContext.getServletContext()
								.getRealPath("/drawing");
			//设置目标文件
			File toFile = new File(uploadPath,fileName);
			
			if (toFile.exists()) {
				 //处理文件名
				 String realname = fileName.substring(fileName.indexOf("_")+1);
				 //设置响应头，控制浏览器下载该文件
		         response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
		         //设置文件ContentType类型，这样设置，会自动判断下载文件类型  
		         response.setContentType("multipart/form-data");  
		         //读取要下载的文件，保存到文件输入流
		         FileInputStream in = new FileInputStream(toFile);
			     //创建输出流
			     OutputStream out = response.getOutputStream();
				 //创建缓冲区
		         byte buffer[] = new byte[4096];
		         int len = 0;
		         //循环将输入流中的内容读取到缓冲区当中
		         while((len=in.read(buffer))!=-1){
		          //输出缓冲区的内容到浏览器，实现文件下载
		             out.write(buffer, 0, len);
		         }  
		            in.close();  
		            out.close();  
		            out.flush(); 
				 
				}else{
					//response.sendRedirect("../error.jsp"); 
				}
		} catch (IOException e) {
			// TODO: handle exception
		}
	}
	
   /**
	* 文件删除
	*/
	public String deleteFile(){
		try {
			HttpServletRequest request=ServletActionContext.getRequest();
			//获取文件名
			String file =  request.getParameter("fileName");
			String fileName = new String(file.getBytes("iso8859-1"),"UTF-8");
			//设置文件目录
			String uploadPath = ServletActionContext.getServletContext()
								.getRealPath("/drawing");
			//设置目标文件
			File toFile = new File(uploadPath,fileName);
			if (toFile.isFile() && toFile.exists()) {  
				toFile.delete();  
		        flag = true;  
		    }else {
		    	flag = false;
			}  
		
		} catch (Exception e) {
			// TODO: handle exception
				flag = false;
		}
		
		return "delef";
	}
	

	/**
	 * 添加采购需求
	 */
	public String saveProcurep(){
	HttpServletRequest request=ServletActionContext.getRequest();

	//获取当前时间
	Date date = new Date();//创建一个时间对象，获取到当前的时间
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置时间显示格式
	String currentDate = sdf.format(date);// 将当前时间格式化为需要的类型
	//设置生成时间
	if (procureProduct.getCreateTime() == null) {
		procureProduct.setCreateTime(Timestamp.valueOf(currentDate));
	}
	//设置修改时间
	procureProduct.setUpdateTime(Timestamp.valueOf(currentDate));
	//设置状态
	if (procureProduct.getStatus() == null) {
		procureProduct.setStatus(0);
	} 
	//设置用户名
	procureProduct.setSysUser("admin");
	
	JSONArray jsonArry = JSONArray.fromObject(skuJsons); // 首先把字符串转成 JSONArray对象
	StringBuffer testDetailStrs = new StringBuffer("");
	
	if(jsonArry.size()>0){
		//循环每一个对象
		for(int i=0;i<jsonArry.size();i++){
			JSONObject etestDetail = jsonArry.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
			
			String skuCode = etestDetail.get("skuCode").toString(); //sku编码
			String cona = etestDetail.get("cona").toString();	//颜色名称
			String szid = etestDetail.get("szid").toString();	//产品尺寸ID
			String purchaseNum = etestDetail.get("purchaseNum").toString();	//采购数量
			String productCode = etestDetail.get("productCode").toString();	//产品编码
			String coloId = etestDetail.get("coloId").toString();	//颜色id
			String colo = etestDetail.get("colo").toString(); //颜色编码
			String szco = etestDetail.get("szco").toString();	//尺寸编码
			
			if(i == jsonArry.size()-1){
				testDetailStrs.append("(''"+productCode+"'',''"+skuCode+"'',''"+colo+"'',''"+cona+"'',''"+szid+"'',''"+coloId+"'',''"+szco+"'',"+purchaseNum+")");
			}else{
				testDetailStrs.append("(''"+productCode+"'',''"+skuCode+"'',''"+colo+"'',''"+cona+"'',''"+szid+"'',''"+coloId+"'',''"+szco+"'',"+purchaseNum+"),");
			}

		}
	}
		testDetailStrs.toString();
		
		flag = procurepBiz.addProductPart(procureProduct,testDetailStrs);
		
		return "add";
	}
	
	
	
	/**
	 * 删除采购需求
	 */
	public String removeProcurep(){
		HttpServletRequest request=ServletActionContext.getRequest();
		//接受页面穿过来的值
		String id= request.getParameter("procId");
		procId=Integer.valueOf(id);
		
		//删除
		flag=procurepBiz.delProcurep(procId);
		
		return "remov";
		
	}
	
	
	/**
	 * 供应商发布
	 */
	public String publishProcurep(){
		HttpServletRequest request=ServletActionContext.getRequest();
		
		//接收页面传过来的值
		JSONArray jsonArry = JSONArray.fromObject(param); // 首先把字符串转成 JSONArray对象
		StringBuffer publishSuin = new StringBuffer("");
		
		if(jsonArry.size()>0){
			//循环每一个对象
			for(int i=0;i<jsonArry.size();i++){
				JSONObject procureInq = jsonArry.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
				
				String pId = procureInq.get("procId").toString(); //sku编码
				procId=Integer.valueOf(pId);
				String suid = procureInq.get("suid").toString();	//颜色名称
				String sendTime = procureInq.get("sendTime").toString();	//产品尺寸ID
				String endTime = procureInq.get("endTime").toString();	//采购数量
				String remark = procureInq.get("remark").toString();	//产品编码
				
				
				if(i == jsonArry.size()-1){
					publishSuin.append("("+pId+",'"+suid+"','"+sendTime+"','"+endTime+"','"+remark+"')");
				}else{
					publishSuin.append("("+pId+",'"+suid+"','"+sendTime+"','"+endTime+"','"+remark+"'),");
				}

			}
			
		}
		publishSuin.toString();
		
		//添加采购发布
		flag=procurepBiz.addProcureInquiry(publishSuin);
		
		//修改状态
		if(flag){
			procureProduct=procurepBiz.getById(procId);
			procureProduct.setStatus(1);
			flag=procurepBiz.mergeprocureProduct(procureProduct);
		}
		
		return "addInquiry";
		
	}
	
	
	
	
	
}
